package com.example.administrator.fagementwc;

public class Change {

    public static byte[] serialize(String message) {
        int totalLength = message.length() + 4;
        byte[] buffer = new byte[totalLength];
        int offset = 0;

        byte[] totalLengthBuffer = intToByte(totalLength);

        System.arraycopy(totalLengthBuffer, 0, buffer, offset, 4);
        offset += 4;

        System.arraycopy(message.getBytes(), 0, buffer, offset, message.length());
        System.out.println("totalLength:" + totalLength);
        return buffer;

    }

    public static String unserialize(byte[] data) {
        int totalLength = byteToInt(data, 0);
        System.out.println("totalLength:" + totalLength);
        return new String(data, 4, totalLength - 4);
    }

    public static byte[] intToByte(int num) {
        byte[] buffer = new byte[4];
        //https://blog.csdn.net/u013556056/article/details/81019509
        for (int i = 0; i < 4; i++) {
            buffer[i] = (byte) (num >> 8 * i);
        }
        return buffer;
    }

    public static int byteToInt(byte[] buffer, int offset) {
        int num = 0;
        for (int i = 0; i < 4; i++) {
            num += (int) (buffer[i + offset] << 8 * i);
        }
        return num;
    }

}
